//webSocket js
import store from "@/store";

const state = {
    webSock: null,
    eventList:[],
    timeout: 5 * 1000,//30秒一次心跳
    timeoutObj: null,//心跳心跳倒计时
    serverTimeoutObj: null,//心跳倒计时
    timeOutNum: null,//断开 重连倒计时
    lockReconnect:false,
    ucId:""
}

const mutations = {
    WEB_SOCKET_INIT:(state,ucId)=>{
        state.ucId = ucId
        const wsUri = "ws://202.107.190.8:10118/wss/webSocket/"+ucId;
        // const wsUri = "wss://ifire.uchung.com/wss/webSocket/"+ucId;
        state.webSock = new WebSocket(wsUri);
        state.webSock.onopen = function () {
            console.log("WebSocket连接成功" + '状态码：'+ state.webSock.readyState)
            let actions = {"type":"online","ucId":ucId};
            state.webSock.send(JSON.stringify(actions))
            start()
        }
        state.webSock.onmessage = function (callBack) {
            console.log( "WebSocket接收到服务端数据"+'数据为：' + callBack.data)
            const  obj = JSON.parse(callBack.data)
            console.log("methodStr:" + obj.type + " dataStr:" + obj)
            switch (obj.type){
                case "heartbeat":
                    reset();
                    break;
                default:
                    state.eventList.push({
                        method:obj.type,
                        data:obj
                    })
                    break;
            }

        }
        state.webSock.onerror=function(e) { //错误
            console.log("WebSocket连接错误!",e);
            reconnect();
        }
        state.webSock.onclose=function(e) { //关闭
            console.log("WebSocket连接关闭！",e);
            reconnect();
        }
    },
    WEB_SOCKET_SEND(state, data) {
        state.webSock.send(JSON.stringify(data));
    },
    WEB_SOCKET_CLOSE(state) {
        state.eventList = []
        let actions = {
            "type": "offline",
            "ucId": state.ucId
        };
        state.webSock.send(JSON.stringify(actions));
        state.webSock.close()
        state.webSock = null
    }
}

const actions = {
    webSocketInit({commit},url) {
        commit('WEB_SOCKET_INIT',url)
    },
    webSocketSend({commit}, data) {
        commit('WEB_SOCKET_SEND', data)
    }
}


function start () { // 开启心跳
    state.timeoutObj && clearTimeout(state.timeoutObj);
    state.serverTimeoutObj && clearTimeout(state.serverTimeoutObj);
    state.timeoutObj = setTimeout(() => {
        // 这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (state.webSock && state.webSock.readyState == 1) { // 如果连接正常
            state.webSock.send(JSON.stringify({"type":"heartbeat","ucId":state.ucId}));
        } else { // 否则重连
            reconnect();
        }
        state.serverTimeoutObj = setTimeout(() => {
            //超时关闭
            state.webSock.close();
        }, state.timeout);
    }, state.timeout)
}

function reconnect () { // 重新连接
    if (!state.webSock) return
    if(state.lockReconnect) return;
    state.lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    state.timeOutNum && clearTimeout(state.timeOutNum);
    state.timeOutNum = setTimeout(() => {
        //新连接
        store.dispatch("webSocket/webSocketInit",state.ucId)
        state.lockReconnect = false;
    }, 5000);
}
function reset () { // 重置心跳
    // 清除时间
    clearTimeout(state.timeoutObj);
    clearTimeout(state.serverTimeoutObj);
    // 重启心跳
    start();
}



export default {
    namespaced: true,
    state,
    mutations,
    actions
}
